package com.jfree.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PreTokenFilter extends ZuulFilter {



//
//    zuul:
//    routes:
//    client1:
//    path: /api1/**
// serviceId: client-1
// client2:
// path: /api2/**
// serviceId: client-2
// prefix: /v1
// retryable: true
//
// #l路由重试，熔断器降级失败？？？,大文件上传绕过disachservletrequest,client2关闭ServerFallback被调用两次，errfilter调用一次


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;//可以动态设置，控制过滤范围
    }

    @Override
    public Object run() throws ZuulException {
        //方法题最好被try-catch包围
        System.out.println("---进入PreTokenFilter---");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("token");
        HttpServletResponse response = requestContext.getResponse();
       // int t = 1 / 0;
        if (StringUtils.isEmpty(token)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("{\"result\":\"false\",\"memo\":\"test\"}");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");

        }else{
            response.setHeader("dawd","uwua");
        }
        return null;
    }
}
